<template>
  <div class="settings-container">
    <el-card shadow="hover" class="settings-card">
      <template #header>
        <div class="header-container">
          <h3>系统设置</h3>
        </div>
      </template>      
    <el-tabs v-model="activeTab">
        <el-tab-pane label="个人信息" name="profile">
          <el-form :model="profileForm" label-width="100px">
            <el-form-item label="用户名">
              <el-input v-model="profileForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="profileForm.name"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="profileForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="profileForm.phone"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveProfileInfo">保存信息</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="修改密码" name="password">
          <el-form :model="passwordForm" label-width="100px">
            <el-form-item label="当前密码">
              <el-input v-model="passwordForm.currentPassword" type="password" show-password></el-input>
            </el-form-item>
            <el-form-item label="新密码">
              <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认新密码">
              <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="changePassword">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>        <el-tab-pane label="系统设置" name="system">
          <el-form label-width="200px">
            <el-form-item label="数据自动刷新">
              <el-switch v-model="systemSettings.autoRefresh"></el-switch>
            </el-form-item>
            <el-form-item label="刷新间隔时间(秒)">
              <el-input-number v-model="systemSettings.refreshInterval" :min="10" :max="300"></el-input-number>
            </el-form-item>
            <el-form-item label="系统主题">
              <el-radio-group v-model="systemSettings.theme">
                <el-radio label="light">浅色</el-radio>
                <el-radio label="dark">暗色</el-radio>
                <el-radio label="auto">跟随系统</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="告警通知">
              <el-checkbox-group v-model="systemSettings.notifications">
                <el-checkbox label="email">邮件通知</el-checkbox>
                <el-checkbox label="push">APP推送</el-checkbox>
                <el-checkbox label="sms">短信通知</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveSystemSettings">保存设置</el-button>
              <el-button @click="resetSystemSettings">重置</el-button>
            </el-form-item>          </el-form>
        </el-tab-pane>

        <el-tab-pane v-if="false" label="API设置" name="api">
          <el-form label-width="200px">            
            <el-form-item label="混合数据模式">
              <el-switch v-model="apiSettings.enableHybridMode"></el-switch>
              <div class="setting-tip">启用后前端将发送API请求验证权限，但使用本地数据渲染界面</div>
            </el-form-item>
            <el-form-item label="API失败时回退到备用数据">
              <el-switch v-model="apiSettings.fallbackToMockOnFailure"></el-switch>
              <div class="setting-tip">启用后，当API请求失败时将自动使用备用数据</div>
            </el-form-item>            
            <el-form-item label="显示数据标记">
              <el-switch v-model="apiSettings.showMockDataIndicator"></el-switch>
              <div class="setting-tip">在使用备用数据时，在控制台和UI中显示指示器</div>
            </el-form-item>
            <el-form-item label="显示悬浮指示器">
              <el-switch v-model="apiSettings.showFloatingIndicator"></el-switch>
              <div class="setting-tip">显示一个可点击的悬浮指示器，可快速切换数据模式</div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveApiSettings">保存API设置</el-button>
              <el-button @click="resetApiSettings">重置</el-button>
              <el-button type="success" @click="testApiConnection">测试API连接</el-button>
            </el-form-item>
            <el-form-item v-if="apiTestResult">
              <el-alert
                :type="apiTestResult.success ? 'success' : 'error'"
                :title="apiTestResult.message"
                :description="apiTestResult.details"
                show-icon
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getUserInfo, updateUserInfo, changePassword as apiChangePassword, getSystemSettings, updateSystemSettings } from '../../api/user';
import { configureHybridApi, hybridConfig, getUseMockData, setUseMockData } from '../../api/hybridApi';
import api from '../../api/index';

export default {
  name: 'UserSettings',
  setup() {
    // 当前活跃标签
    const activeTab = ref('profile');
    
    // 用户ID
    const userId = localStorage.getItem('userId');
    
    // 个人信息表单
    const profileForm = reactive({
      username: '',
      name: '',
      email: '',
      phone: ''
    });
    
    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const response = await getUserInfo(userId);
        const user = response.data;
        
        profileForm.username = user.username;
        profileForm.name = user.name || '';
        profileForm.email = user.email || '';
        profileForm.phone = user.phone || '';
      } catch (error) {
        console.error('获取用户信息失败:', error);
        ElMessage.error('获取用户信息失败');
      }
    };
    
    // 密码表单
    const passwordForm = reactive({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    });    // 系统设置
    const systemSettings = reactive({
      autoRefresh: true,
      refreshInterval: 30,
      theme: 'light',
      notifications: ['email', 'push']
    });
      // API设置
    const apiSettings = reactive({
      enableHybridMode: true,
      fallbackToMockOnFailure: true,
      showMockDataIndicator: true,
      showFloatingIndicator: true
    });
    
    // API测试结果
    const apiTestResult = ref(null);
    
    // 加载系统设置
    const loadSystemSettings = async () => {
      try {
        const response = await getSystemSettings(userId);
        if (response && response.data) {
          // 使用API返回的设置更新本地对象
          Object.assign(systemSettings, response.data);
        }
      } catch (error) {
        console.error('加载系统设置失败:', error);
        ElMessage.error('加载系统设置失败');
      }
    };
    
    // 保存个人信息
    const saveProfileInfo = async () => {
      try {
        await updateUserInfo(userId, {
          name: profileForm.name,
          email: profileForm.email,
          phone: profileForm.phone
        });
        ElMessage.success('个人信息保存成功');
      } catch (error) {
        console.error('保存个人信息失败:', error);
        ElMessage.error('保存个人信息失败，请稍后再试');
      }
    };
    
    // 修改密码
    const changePassword = async () => {
      if (!passwordForm.currentPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
        ElMessage.warning('请填写完整的密码信息');
        return;
      }
      
      if (passwordForm.newPassword !== passwordForm.confirmPassword) {
        ElMessage.error('两次输入的新密码不一致');
        return;
      }
      
      try {
        // 首先需要验证当前密码是否正确
        const userInfo = await getUserInfo(userId);
        if (userInfo.data.password !== passwordForm.currentPassword) {
          ElMessage.error('当前密码不正确');
          return;
        }
        
        // 更新密码
        await apiChangePassword(userId, {
          oldPassword: passwordForm.currentPassword,
          newPassword: passwordForm.newPassword
        });
        
        ElMessage.success('密码修改成功，请重新登录');
        // 清除登录状态，重定向到登录页
        localStorage.removeItem('token');
        localStorage.removeItem('userId');
        localStorage.removeItem('userInfo');
        
        setTimeout(() => {
          window.location.href = '/login';
        }, 1500);
      } catch (error) {
        console.error('修改密码失败:', error);
        ElMessage.error('修改密码失败，请稍后再试');
      }    };
    
    // 重置系统设置
    const resetSystemSettings = () => {
      systemSettings.autoRefresh = true;
      systemSettings.refreshInterval = 30;
      systemSettings.theme = 'light';
      systemSettings.notifications = ['email', 'push'];
      
      // 同时从localStorage中删除
      localStorage.removeItem('systemSettings');
      
      ElMessage.info('系统设置已重置');
    };
    
    // 保存系统设置同时将其存储在 localStorage 中
    const saveSystemSettings = async () => {
    try {
      await updateSystemSettings(userId, systemSettings);
      ElMessage.success('系统设置保存成功');
    } catch (error) {
      console.error('保存系统设置失败:', error);
      ElMessage.error('保存系统设置失败');
    }
  };
  // 加载API设置
  const loadApiSettings = () => {
    // 从localStorage和hybridConfig获取设置
    apiSettings.enableHybridMode = getUseMockData();
    apiSettings.fallbackToMockOnFailure = hybridConfig.fallbackToMockOnFailure;
    apiSettings.showMockDataIndicator = hybridConfig.showMockDataIndicator;
    
    // 获取悬浮指示器设置
    const floatingIndicator = localStorage.getItem('showFloatingIndicator');
    apiSettings.showFloatingIndicator = floatingIndicator === null ? true : floatingIndicator === 'true';
  };
  
  // 保存API设置
  const saveApiSettings = () => {    try {      // 更新数据状态
      setUseMockData(apiSettings.enableHybridMode);
      
      // 配置混合API
      configureHybridApi({
        enableHybridMode: apiSettings.enableHybridMode,
        fallbackToMockOnFailure: apiSettings.fallbackToMockOnFailure,
        showMockDataIndicator: apiSettings.showMockDataIndicator
      });
      
      // 保存浮动指示器设置
      localStorage.setItem('showFloatingIndicator', apiSettings.showFloatingIndicator);
      
      ElMessage.success('API设置保存成功');
    } catch (error) {
      console.error('保存API设置失败:', error);
      ElMessage.error('保存API设置失败');
    }
  };
    // 重置API设置
  const resetApiSettings = () => {
    apiSettings.enableHybridMode = true;
    apiSettings.fallbackToMockOnFailure = true;
    apiSettings.showMockDataIndicator = true;
    apiSettings.showFloatingIndicator = true;
    
    // 保存重置后的设置
    saveApiSettings();
    
    ElMessage.info('API设置已重置');
  };
  
  // 测试API连接
  const testApiConnection = async () => {
    apiTestResult.value = {
      success: false,
      message: '正在测试API连接...',
      details: '请稍候...'
    };
    
    try {
      // 测试后端API连接
      const response = await api.get('/auth/test');
      
      apiTestResult.value = {
        success: true,
        message: 'API连接测试成功',
        details: `服务器状态: ${response.code === 200 ? '正常' : '返回异常状态码'}\n` +
                `当前模式: ${apiSettings.enableHybridMode ? '混合数据模式' : '标准API模式'}`
      };
    } catch (error) {
      apiTestResult.value = {
        success: false,
        message: 'API连接测试失败',
        details: `错误信息: ${error.message || '未知错误'}\n` +
                `建议: 请检查网络连接或后端服务器状态`
      };
      console.error('API连接测试失败:', error);
    }
  };
  
  // 页面加载时获取用户信息和设置
  onMounted(() => {
    fetchUserInfo();
    loadSystemSettings();
    loadApiSettings();
  });
  
  return {
    activeTab,
    profileForm,
    passwordForm,
    systemSettings,
    apiSettings,
    apiTestResult,
    saveProfileInfo,
    changePassword,
    saveSystemSettings,
    resetSystemSettings,
    loadSystemSettings,
    saveApiSettings,
    resetApiSettings,
    testApiConnection
  };
  }
};
</script>

<style scoped>
.settings-container {
  padding: 10px;
}

.settings-card {
  min-height: 600px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.el-tabs {
  margin-top: 20px;
}

.el-form {
  max-width: 600px;
  margin: 0 auto;
}

.setting-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}

.el-alert {
  margin-top: 15px;
}
</style>
